package x.ovo.wechat.bot.http.request.group;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.http.request.ApiRequest;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 创建组请求
 *
 * @author ovo on 2024/05/06.
 * @since 1.0.0
 */
public class CreateGroupRequest extends ApiRequest<Boolean> {

    private final String groupName;
    private final List<String> members;

    public CreateGroupRequest(LoginSession session, String groupName, List<String> members) {
        super(session);
        this.groupName = groupName;
        this.members = members;
    }

    @Override
    public String getUrl() {
        return UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.CREATE_GROUP)
                .addQuery("lang", "zh_CN")
                .addQuery("r", System.currentTimeMillis())
                .build();
    }

    @Override
    public Map<String, Object> getParameters() {
        JSONArray array = JSONUtil.createArray();
        members.forEach(m -> array.put(JSONUtil.createObj().set("UserName", m)));
        return JSONUtil.createObj()
                .set("MemberCount", members.size())
                .set("MemberList", array)
                .set("Topic", groupName)
                .getRaw();
    }

    @Override
    public String getMethod() {
        return POST;
    }

    @Override
    public boolean isJson() {
        return true;
    }

    @Override
    public Function<String, Boolean> responseHandler() {
        return s -> JSONUtil.parseObj(s).getJSONObject("BaseResponse").getInt("Ret") == 0;
    }
}
